package cn.wei.youvierpc.server.tcp;

import cn.wei.youvierpc.server.HttpServer;
import cn.wei.youvierpc.server.HttpServerHandler;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.net.NetServer;
import io.vertx.core.parsetools.RecordParser;

public class VertxTcpServer implements HttpServer {
    @Override
    public void doStart(int port) {
        Vertx vertx = Vertx.vertx();

        //vert.x创建服务器

        NetServer netServer = vertx.createNetServer();

        netServer.connectHandler(netSocket -> {
            RecordParser recordParser = RecordParser.newFixed(8);
            recordParser.setOutput(new Handler<Buffer>() {
                int size = -1;
                Buffer resultBuffer = Buffer.buffer();
                @Override
                public void handle(Buffer buffer) {
                    if (size == -1) {
                        size = resultBuffer.getInt(4);
                        recordParser.fixedSizeMode(size);

                        resultBuffer.appendBuffer(buffer);
                    } else {
                        resultBuffer.appendBuffer(buffer);
                        System.out.println(resultBuffer.toString());

                        recordParser.fixedSizeMode(8);
                        size = -1;
                        resultBuffer = Buffer.buffer();
                    }

                }
            });
            netSocket.handler(recordParser);
        });

        //启动服务器并监听指定端口
        netServer.listen(port, httpServerAsyncResult -> {
            if (httpServerAsyncResult.succeeded()) {
                System.out.println("TCP Server is now listening on the port " + port);
            } else {
                System.out.println("Fail to start TCP server" + httpServerAsyncResult.cause());
            }
        });
    }

    private byte[] handleRequest(byte[] requestData) {
        return "hello, client".getBytes();
    }

    public static void main(String[] args) {
        new VertxTcpServer().doStart(8888);
    }
}
